package com.syswin.lhztest.nio.bio;

import java.io.*;
import java.net.ServerSocket;
import java.net.Socket;

/**
 * 基于Tcp，支持http协议
 * @author:lhz
 * @date:2018/12/10 21:09
 */
public class BIOServer1 {

	public static void main(String[] args) throws Exception {
		//jdk 底层调用socket api 监听端口
		ServerSocket serverSocket = new ServerSocket(8080);
		System.out.println("tomcat 服务器启动成功");
		while (!serverSocket.isClosed()) {
			Socket request = serverSocket.accept();
			System.out.println("收到新连接：" + request.toString());
			try {
				InputStream inputStream = request.getInputStream();
				BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));
				String msg;
				while ((msg = reader.readLine()) != null) {
					if (msg.length() == 0) {
						break;
					}
					System.out.println(msg);
				}
				System.out.println("收到数据，来自："+request.toString());

				//返回一个数据
				//响应结果 200
				OutputStream  outputStream = request.getOutputStream();
				outputStream.write("HTTP/1.1 200 OK\r\n".getBytes());
				outputStream.write("Content-Length: 11\r\n\r\n".getBytes());
				outputStream.write("Hello World".getBytes());
				outputStream.flush();
			} catch (IOException e) {

			}
		}

	}
}
